package org.example.java.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * Listing 4.1  of <i>Netty in Action</i>
 */
public class PlainOioServer {

  public static void main(String[] args) {
    try {
      serve(2404);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void serve(int port) throws IOException {
    final ServerSocket socket = new ServerSocket(port);
    try {
      while (true) {
        final Socket clientSocket = socket.accept();
        System.out.println("Accepted connection from " + clientSocket);

        new Thread(new Runnable() {
          @Override
          public void run() {
            OutputStream out;
            try {
              InputStream in = clientSocket.getInputStream();
              byte[] bytes = new byte[1024 * 1024];
              int len = in.read(bytes);
              System.out.println("receive : " + new String(bytes, 0, len));
              out = clientSocket.getOutputStream();
              out.write("Hi!\r\n".getBytes(Charset.forName("UTF-8")));
              out.flush();
              clientSocket.close();

            } catch (IOException e) {
              e.printStackTrace();
              try {
                clientSocket.close();
              } catch (IOException ex) {
                // ignore on close
              }
            }
          }
        }).start();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
